# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models, _
import time

import logging

_logger = logging.getLogger(__name__)


class FapiaoPaper(models.Model):
    _inherit = "fp.fapiao.paper"

    draw_ids = fields.One2many(
        'fp.fapiao.draw', 'fapiao_id', string="Draws", copy=False)
    draw_id = fields.Many2one(
        'fp.fapiao.draw',  string="Draw", compute="_compute_draw_id", copy=False)

    @api.depends('draw_ids')
    def _compute_draw_id(self):
        for one in self:
            if one.draw_ids:
                one.draw_id = one.draw_ids[0]
            else:
                one.draw_id = self.env['fp.fapiao.draw']

    def action_draw(self):
        self2 = self.search([
            ('id', 'in', self.ids),
            ('type', '=', 'out_invoice'),
            ('state', '=', 'confirmed'),
        ])

        return self.env['fp.fapiao.draw'].find_by_fapiao(self2)

    def action_draw_request(self):
        fp_draw = self.action_draw()
        fp_draw.action_request()

    def action_draw_query(self):
        self2 = self.search([
            ('id', 'in', self.ids),
            ('type', '=', 'out_invoice'),
            ('state', '=', 'doing'),
        ])
        draws = self2.mapped('draw_id')

        if draws:
            draws.action_query()

    def action_draw_invalid(self):
        # _logger.info('fp.fapiao, action_draw_invalid, :%s,', self)
        self2 = self.search([
            ('id', 'in', self.ids),
            ('type', '=', 'out_invoice'),
            ('state', '=', 'done'),
        ])
        draws = self2.mapped('draw_id')

        # _logger.info('fp.fapiao, action_draw_invalid,draws :%s,', draws)

        if draws:
            # _logger.info('fp.fapiao, action_draw_invalid,draws2:%s,', draws)
            draws.action_invalid()

    def action_draw_print(self):
        self2 = self.search([
            ('id', 'in', self.ids),
            ('type', '=', 'out_invoice'),
            ('state', '=', 'done'),
        ])
        draws = self2.mapped('draw_id')

        if draws:
            draw_res = draws.action_print()

            res = []
            for one in draw_res:
                one2 = one.copy()
                obj = self.env['fp.fapiao.draw']
                one2['id'] = obj.browse(one['id']).fapiao_id.id

                res.append(one2)

            print('fp action_draw_print', res)

            return res

        return []


class FapiaoDraw(models.Model):
    _name = "fp.fapiao.draw"
    _inherit = ['fp.fapiao.operate.mixin']
    _description = "Fapiao Draw"
    # _order = 'sequence, name'

    def _default_taxmachine_id(self):
        fpuser = self.env.user._get_fp_user()

        if fpuser.taxmachine_id:
            return fpuser.taxmachine_id
        else:
            company_id = self.env.user.company_id
            return self.env['fp.company.taxmachine'].search(
                [('company_id', '=', company_id.id)], limit=1)

    def _default_payee_name(self):
        return self.env.user._get_fp_user().payee_name

    def _default_checker_name(self):
        return self.env.user._get_fp_user().checker_name

    def _default_drawer_name(self):
        return self.env.user._get_fp_user().drawer_name

    fapiao_id = fields.Many2one(
        domain=[('type', 'in', ['out_invoice'])],
        help="待开票及开票结果数据")

    state = fields.Selection(
        selection_add=[
            # ('draft', 'Draft'),  # 初值
            ('requesting', 'Requesting'),  # 开票请求中  临时状态=等待中=返回数据
            ('requested', 'Requested'),  # 开票请求完成 获得 流水号 稳定状态
            ('reread', 'reread'),  # 待重新查询. 稳定状态
            ('reading', 'reading'),  # 用流水号 查询中. 临时状态

            # todo : 被红冲
            # ('refunded', 'refunded'),  # 查询完成 . 末状态  稳定状态
            ('be_invalid', 'be_invalid'),  # 查询完成 . 末状态  稳定状态
            ('error', 'error'),  # 查询完成 . 末状态  稳定状态

            # ('done', 'done'),  # 查询完成 . 末状态  稳定状态

            # ('printing', 'Printing'),  # 打印中. 临时状态
            # ('printed', 'printed'),  # 已打印. 末状态  稳定状态
        ],
        string="开票控制", help="开票控制")

    api_draw_id = fields.Many2one(
        'fp.api.draw',
        string='Api Draw Provider',
        compute='_compute_api_draw_id')

    @api.depends('company_id')
    def _compute_api_draw_id(self):
        for one in self:
            api_company = self.env[
                'fp.api.draw.company'].search_by_company(one.company_id)

            one.api_draw_id = api_company.api_draw_id

    taxmachine_id = fields.Many2one(
        'fp.company.taxmachine', 'taxmachine_id',
        domain="[('company_id', '=', company_id)]",
        default=_default_taxmachine_id,
        required=True, index=True)

    taxmachine_code = fields.Char(
        string='taxmachine_code', related="taxmachine_id.code")

    payee_name = fields.Char(string='收款人', default=_default_payee_name)
    checker_name = fields.Char(string='复核', default=_default_checker_name)
    drawer_name = fields.Char(string='开票人', default=_default_drawer_name)

    invoice_type = fields.Selection(
        selection=[
            ('vat_special', '增值税专用发票'),
            ('vat_general', '增值税普通发票'),
            ('vat_general_e', '增值税电子普通发票'),
            ('vat_special_e', '增值税电子专用发票'),
            # ('40', '货物运输业增值税专用发票'),
            # ('50', '机动车销售统一发票'),
            # ('60', '卷式发票'),
            # ('70', '二手车发票'),
            # ('80', '通行费发票'),
        ], string='Fapiao Type', default='vat_general_e')

    @api.onchange('user_id')
    def _onchage_for_user_id(self):
        for one in self:
            fpuser = one.user_id._get_fp_user()
            if fpuser:
                one.payee_name = fpuser.payee_name
                one.checker_name = fpuser.checker_name
                one.drawer_name = fpuser.drawer_name
                if fpuser.taxmachine_id:
                    one.taxmachine_id = fpuser.taxmachine_id

    def action_request(self):
        self2 = self.search(
            [('id', 'in', self.ids), ('state', '=', 'draft')])

        if self2:
            for one in self2:
                one.state = 'requesting'
                one.fapiao_id.state = 'doing'

            api_draw_id = self2[0].api_draw_id
            request_method = api_draw_id._request_method_get()
            result = request_method(self2)

            for rec in result:
                one = self.browse(rec['id'])
                one.write({'state': 'requested'})

    def action_query(self):
        # # 开票结果 查询请求

        self2 = self.search(
            [('id', 'in', self.ids),
             ('state', 'in', ['requested', 'reread'])])

        if self2:
            for one in self2:
                one.write({'state': 'reading'})

            api_draw_id = self2[0].api_draw_id
            query_method = api_draw_id._query_method_get()
            records = query_method(self2)

            for record in records:

                # _logger.info("Nuonuo call to read fapiao return: %s" % record)

                one = self.browse(record['id'])
                one.state = record['state']

                values_for_fapiao = {
                    'attachment_id': record.get('attachment_id'),
                    'taxmachine_code': record['taxmachine_code'],
                    'payee_name': record['payee_name'],
                    'checker_name': record['checker_name'],
                    'drawer_name': record['drawer_name'],

                    'date_fapiao': record['date_fapiao'],
                    'time_fapiao': record['time_fapiao'],
                    'invoice_code': record['invoice_code'],
                    'invoice_number': record['invoice_number'],
                    'check_code': record.get('check_code'),
                    'amount_untaxed': record['amount_untaxed'],
                    'amount_tax': record['amount_tax'],
                    'amount_total': record['amount_total'],

                    'line_ids': [(1, line['id'], {
                        'tax_ratio': line['tax_ratio'],
                        'quantity': line['quantity'],
                        'amount_untaxed': line['amount_untaxed'],
                        'amount_tax': line['amount_tax'],
                        'amount_total': line['amount_total'],
                        'price_untax': line['price_untax'],
                        'price_unit': line['price_unit'],
                    }) for line in record['line_ids']],
                }

                if record['state'] in ['done', 'error', 'refunded', 'be_invalid']:
                    values_for_fapiao['state'] = record['state']

                one.fapiao_id.write(values_for_fapiao)

    def action_invalid(self):
        # # 发票 作废
        # _logger.info('fp.fapiao.draw , action_invalid,:%s,', self)

        self2 = self.search(
            [('id', 'in', self.ids), ('state', 'in', ['done'])])

        # _logger.info('fp.fapiao.draw 2, action_invalid,:%s,', self2)

        if self2:
            api_draw_id = self2[0].api_draw_id
            invalid_method = api_draw_id._invalid_method_get()

            # _logger.info('fp.fapiao.draw 3, invalid_method,:%s,',
            #              invalid_method)

            result = invalid_method(self2)

            # print('action_invalid', result)

            # _logger.info('action_invalid, ok1:%s,', self)
            # _logger.info('action_invalid, ok2:%s,', self2)
            # _logger.info('action_invalid, ok3:%s,', result)

            for rec in result:
                one = self.browse(rec['id'])
                one.write({'state': 'be_invalid'})

    def action_print(self):
        # # 开票结果 打印

        self2 = self.search(
            [('id', 'in', self.ids), ('state', 'in', ['done'])])

        if self2:

            api_draw_id = self2[0].api_draw_id
            print_method = api_draw_id._print_method_get()
            records = print_method(self2)

            print('action_print', records)

            return records

        return []

    def action_reread(self):
        self2 = self.search(
            [('id', 'in', self.ids),
             ('state', 'in', ['reading', 'done', 'refunded', 'be_invalid',
                              'error'])])

        if self2:
            for one in self2:
                one.state = 'reread'
                one.fapiao_id.state = 'doing'
